package com.ts.api.module.test.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.log.Log;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.channel.entity.qo.ChannelUserQO;
import com.ts.api.module.channel.service.ChannelUserService;
import com.ts.api.module.product.entity.bo.ProductAmountBO;
import com.ts.api.module.product.entity.po.ProductApplyFlowPO;
import com.ts.api.module.product.entity.po.ProductPO;
import com.ts.api.module.product.entity.po.ProductPlanPO;
import com.ts.api.module.product.entity.qo.ProductApplyFlowQO;
import com.ts.api.module.product.service.ProductAmountService;
import com.ts.api.module.product.service.ProductApplyFlowService;
import com.ts.api.module.product.service.ProductPlanService;
import com.ts.api.module.product.service.ProductPlanTypeService;
import com.ts.api.module.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.gitee.apanlh.util.base.CollUtils.find;
import static com.gitee.apanlh.util.base.CollUtils.findOne;


/**
 *
 *  @author Pan
 */
@RestController
@RequestMapping("/test/api/check")
public class ApiTestCheckController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ProductApplyFlowService productApplyFlowService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductPlanService productPlanService;
    @Autowired
    private ChannelUserService channelUserService;
    @Autowired
    private ProductPlanTypeService productPlanTypeService;
    @Autowired
    private ProductAmountService productAmountService;

    /**
     *  恢复自有渠道->下游账单缺失
     *
     *  @author Pan
     *  @param  requestVO   请求信息
     *  @return ResultVO
     */
    @RequestMapping("/temp")
    public ResultVO<?> checkPlat1(@RequestParamVo RequestVO requestVO) {
        String startTime = "2025-07-01 00:00:00";
        String endTime = "2025-08-01 23:59:59";

        String sql = "select loan_product_id, loan_product_plan_id, phone_md5, create_time from loan_product_apply_flow where `status` = 11 and api_client_id is null and create_time >= '{startTime}' and create_time <= '{endTime}' and not EXISTS( select phone_md5, loan_product_id, loan_product_plan_id from loan_product_bill where loan_product_bill.phone_md5 = loan_product_apply_flow.phone_md5 and loan_product_bill.loan_product_id = loan_product_apply_flow.loan_product_id and loan_product_bill.loan_product_plan_id = loan_product_apply_flow.loan_product_plan_id and create_time >= '{startTime}' and create_time <= '{endTime}')";
        sql = sql.replace("{startTime}", startTime).replace("{endTime}", endTime);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        if (ValidParam.isEmpty(maps)) {
            return ResultVO.suc("无缺省值");
        }

        Integer count = 0;
        BigDecimal restore = new BigDecimal(0);

        //  搜索流程
        for (Map<String, Object> map: maps) {
            long productId = Long.parseLong(String.valueOf(map.get("loan_product_id")));
            long productPlanId = Long.parseLong(String.valueOf(map.get("loan_product_plan_id")));
            String phoneMd5 = String.valueOf(map.get("phone_md5"));

            ProductApplyFlowQO qo = ProductApplyFlowQO.createByPhoneMd5(phoneMd5);
            qo.setProductId(productId);
            qo.setProductPlanId(productPlanId);
            qo.setStartTime(startTime);
            qo.setEndTime(endTime);
            //  获取撞库成功数据/进件数据
            qo.setStatusList(CollUtils.newArrayList(21, 11));

            //  获取流程数据
            List<ProductApplyFlowPO> listFlow = productApplyFlowService.list(qo);
            if (ValidParam.isEmpty(listFlow)) {
                Log.get().info("获取流程数据失败");
                continue;
            }

            List<ProductApplyFlowPO> listSucFlow = find(listFlow, t -> t.getStatus().equals(11));
            if (ValidParam.isEmpty(listSucFlow)) {
                Log.get().info("获取进件流程数据失败");
                continue ;
            }

            ProductApplyFlowPO applySuc = listSucFlow.getFirst();
            Long loanProductId = applySuc.getLoanProductId();
            Long loanProductPlanId = applySuc.getLoanProductPlanId();
            //  进件请求数据
            String reqData = applySuc.getReqData();

            ProductPO productPO = productService.get(loanProductId);
            ProductPlanPO productPlanPO = productPlanService.get(loanProductPlanId);
//
//            //  解密数据
//            ApiConvertHandler planHandler = apiPlanConvertContext.getPlanHandler(productPO, productPlanPO);

            //  获取撞库数据
            ProductApplyFlowPO dataExchangeSuc = findOne(listFlow, t -> t.getStatus().equals(21) && t.getLoanProductId().equals(loanProductId) && t.getLoanProductPlanId().equals(loanProductPlanId));

            //  获取平台计划
            boolean hasPlatform = productPlanTypeService.hasPlatformPlan(productPlanPO);
            BigDecimal originalPrice = null;
            if (hasPlatform) {
                String respData = dataExchangeSuc.getRespData();
                RespPlatformMultiPhoneMaskDataExchange respMultiPhoneMask = JsonUtils.toBean(respData, RespPlatformMultiPhoneMaskDataExchange.class);
                //  获取原始撞库apply对应进件apply数据
                List<RespPlatformPhoneMaskDataExchange> listPhoneMask = respMultiPhoneMask.getListPhoneMask();
                if (listPhoneMask.size() > 1) {
                    continue;
                }
                RespPlatformPhoneMaskDataExchange first = listPhoneMask.getFirst();
                //  获取价格
                originalPrice = first.getPrice();
            }

            //  获取用户数据
            ChannelUserQO channelUserQOByPhone = ChannelUserQO.createPhoneMd5(phoneMd5);
            ChannelUserRegisterPO channelUserRegisterPO = channelUserService.get(channelUserQOByPhone);

            //  下游扣款
            ProductAmountBO productAmountBO = new ProductAmountBO();
            productAmountBO.setProductId(productPlanPO.getLoanProductId());
            productAmountBO.setProductPlanId(productPlanPO.getId());
            productAmountBO.setUserId(channelUserRegisterPO.getId());
            productAmountBO.setPhoneMd5(channelUserRegisterPO.getPhoneMd5());
            productAmountBO.setLoanChannelId(dataExchangeSuc.getLoanChannelId());
            productAmountBO.setApiClientId(dataExchangeSuc.getApiClientId());
            productAmountBO.setOriginalPrice(originalPrice);
            productAmountBO.setHasPlatform(hasPlatform);
            productAmountBO.setHasLocalExist(Boolean.FALSE);
            productAmountBO.setCreateTime(dataExchangeSuc.getCreateTime());
            productAmountBO.setUpdateTime(DateUtils.currentTime());
            BigDecimal deduct = productAmountService.deduct(productAmountBO);
            count++;

            restore = restore.add(deduct);
            Log.get().info("修复次数:{}, 主体名称:{}, 计划名称:{}, 单价:{}, 总修复金额:{}", count, productPO.getName(), productPlanPO.getDisplayName(), deduct, restore.toString());
        }

        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("总修复次数", count);
        resultMap.put("总修复金额", restore);
        return ResultVO.suc(resultMap);
    }
}
